package com.ch.ms.server.login.packet.handler;

import com.ch.ms.dto.MapleServerDto;
import com.ch.ms.dto.MapleWorldServerDto;
import com.ch.ms.server.base.MaplePacketHandler;
import com.ch.ms.server.base.client.MapleClientSession;
import com.ch.ms.server.packet.LoginRequestPacket;
import com.ch.ms.server.packet.LoginResultPacket;
import com.ch.ms.service.account.ChmsAccountService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.ch.ms.server.base.client.ClientAttributeKeys.LOGGED_ATTR_KEY;


/**
 * 客户端登录
 */
@Component
@Slf4j
public class LoginRequestPacketHandler implements MaplePacketHandler<LoginRequestPacket> {


    private final ChmsAccountService accountService;

    @Autowired
    public LoginRequestPacketHandler(ChmsAccountService accountService) {
        this.accountService = accountService;
    }


    @Override
    public void handle(MapleClientSession clientSession, LoginRequestPacket packet) {


        if (clientSession.getBooleanAttribute(LOGGED_ATTR_KEY, false))
            log.error("客户端 {} 已登录.", clientSession);
        else {
            boolean loginRes = accountService.login(packet.getAccount(), packet.getPassword());
            clientSession.setAttribute(LOGGED_ATTR_KEY, loginRes);
            clientSession.setAccount(accountService.findByUserName(packet.getAccount()));
            clientSession.sendPacket(
                    LoginResultPacket.builder().success(loginRes).worldServers(
                            Lists.newArrayList(MapleWorldServerDto.builder().name("安徽一区").host("localhost").port(1024).channels(

                                    Lists.newArrayList(

                                            MapleServerDto.mapleServerBuilder().name("频道1").host("localhost").port(9981).build(),
                                            MapleServerDto.mapleServerBuilder().name("频道2").host("localhost").port(9982).build(),
                                            MapleServerDto.mapleServerBuilder().name("频道3").host("localhost").port(9983).build(),
                                            MapleServerDto.mapleServerBuilder().name("频道4").host("localhost").port(9984).build()
                                    )
                            ).build())
                    ).build());


        }


    }
}
